package com.phkj.qdh.ui

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import cn.com.cybertech.pdk.OperationLog
import cn.com.cybertech.pdk.UserInfo
import cn.com.cybertech.pdk.auth.Oauth2AccessToken
import cn.com.cybertech.pdk.auth.PstoreAuthListener
import cn.com.cybertech.pdk.auth.sso.SsoHandler
import cn.com.cybertech.pdk.exception.PstoreAuthException
import cn.com.cybertech.pdk.exception.PstoreException
import com.phkj.qdh.BuildConfig
import com.phkj.qdh.base.BaseVM.Companion.STATE_FAIL
import com.phkj.qdh.base.BaseVM.Companion.STATE_LOADING
import com.phkj.qdh.base.BaseVM.Companion.STATE_SUCCESS
import com.phkj.qdh.databinding.ActivityLoginBinding
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.SPSUtils
import com.phkj.qdh.utils.SPS_TOKEN
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.requestIO
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding

    private lateinit var vm: LoginVM

    private  var mSsoHandler: SsoHandler? = null

    private var mOauth2AccessToken: Oauth2AccessToken? = null

    private val CLIENT_ID = BuildConfig.CLIENT_ID
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        vm = ViewModelProvider(this, getLoginVMProvider())[LoginVM::class.java]

        binding.run {
            btnLogin.setOnClickListener {
//
//
                val hashMap = HashMap<String, Any?>()
                hashMap["idCard"] = binding.edt.text.toString()
                vm.login(hashMap)
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                vm.uiState.collectLatest {
                    when (it) {
                        STATE_LOADING -> {
                            LogUtil.E("加载中")
                            binding.pb.visible()
                        }

                        STATE_FAIL -> {
                            LogUtil.E("加载失败")
                            binding.pb.gone()
                        }

                        STATE_SUCCESS -> {
                            LogUtil.E("加载成功")
                            binding.pb.gone()
                        }

                        else -> {
                            binding.pb.gone()
                        }
                    }
                }
            }
        }

        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                vm.userBean.collectLatest {
                    SPSUtils.put(SPS_TOKEN, it)
                    val intent = Intent(this@LoginActivity, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }
            }
        }

        requestIO {
            try {
//                val pstoreAPIImpl = PstoreAPIImpl()
//                pstoreAPIImpl.requestUserInfo(this@LoginActivity,BuildConfig.CLIENT_ID,)
                val dta = UserInfo.getUser(this@LoginActivity)
                val id = dta.idCard
                val hashMap = HashMap<String, Any?>()
                hashMap["idCard"] = id
                vm.login(hashMap)
                OperationLog.logging(
                    this@LoginActivity,
                    BuildConfig.REG_ID,
                    "用户关联登陆",
                    0,
                    1,
                    2,
                    "获取当前登陆当用户身份证调取后端接口，验证是否能进行后续操作"
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    inner class AuthListener : PstoreAuthListener {
        override fun onComplete(accessToken: Oauth2AccessToken) {
            val expiresTime = accessToken.expiresTime
            val currentTimeMillis = System.currentTimeMillis()
           /* Log.w(
                TAG,
                "onComplete: \ncurrentTimeMillis = " + currentTimeMillis + "\nexpiresTime = " + expiresTime + "\n" + (currentTimeMillis - expiresTime)
            )*/
            // 若当前时间大于过期时间，则表示token已经过期，需要重新获取以更新
            if (currentTimeMillis < expiresTime) {
                mOauth2AccessToken = accessToken
//                dismissProgressDialog()
//                showContent(accessToken.toBundle())
            } else {
                mSsoHandler?.authorizeRefresh(AuthListener())
            }
        }

        override fun onPstoreException(pstoreException: PstoreException) {
//            dismissProgressDialog()
            if (pstoreException is PstoreAuthException) {
                val e = pstoreException
                when (e.errorCode) {
                    PstoreAuthException.ERROR_CLIENTID_NULL -> {}
                    PstoreAuthException.ERROR_CLIENTID_ILLEGAL -> {}
                    PstoreAuthException.ERROR_GRANT_CODE_ILLEGAL -> {}
                    else -> {}
                }
//                showError(
//                    String.format(
//                        "code: %s\ntype: %s\nmessage: %s",
//                        e.errorCode,
//                        e.errorType,
//                        e.message
//                    )
//                )
            } else {
                // Unknown exception. pstoreException.getMessage()
//                onException(pstoreException)
            }
        }

        override fun onCancel() {
//            dismissProgressDialog()
        }
    }
}